package com.xq.shop.controller.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.xq.shop.po.Category;
import com.xq.shop.service.admin.IBaseService;
import com.xq.shop.service.admin.ICategoryService;
import com.xq.shop.util.AdminServiceFactory;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.SearchObject;
import com.xq.shop.vo.RespMsg.Result;

@Controller
@RequestMapping("/admin/")
public class CategoryController extends BaseController<Category>{

	private ICategoryService categoryService = AdminServiceFactory.getCategoryService();
	
	@Override
	public IBaseService<Category> getService() {
		return categoryService;
	}
	
	@RequestMapping("category_save.do")
	public ModelAndView save(Category category, HttpServletResponse response) throws Exception{
		
		categoryService.saveOrUpdate(category);
		ModelAndView modelAndView = new ModelAndView("admin/product/category_list");
		modelAndView.addObject(new RespMsg(Result.success, "保存成功"));
		return modelAndView;
	}
	
	@RequestMapping("category_list.do")
	@ResponseBody
	public String list(SearchObject search){
		return GsonUtil.toJson(categoryService.get(search), new ExclusionStrategy() {
			
			@Override
			public boolean shouldSkipField(FieldAttributes f) {
				return "params".equals(f.getName());
			}
			
			@Override
			public boolean shouldSkipClass(Class<?> clazz) {
				return false;
			}
		});
	}
	
	@RequestMapping("category_edit.do")
	public ModelAndView edit(String id, HttpServletResponse response){
		
		ModelAndView view = new ModelAndView("admin/product/category_edit");
		Category category;
		if(id != null){
			category = categoryService.get(Long.parseLong(id));
		} else {
			category = new Category();
		}
		
		if(category == null){
			//TODO go to 404
			return view;
		} else {
			
			view.addObject("entity", category);
			
			//获取所有一级分类
			List<Category> category_List = new ArrayList<Category>();
			Category tmp = new Category();
			category_List.add(tmp);
			category_List.addAll(categoryService.getByPID(0));
			view.addObject("categoryList", category_List);
			return view;
		}
	}
	
	@RequestMapping("category_delete.do")
	public void delete(String id, HttpServletResponse response){
		
		super.delete(id, response);
	}
}
